<template>
  <div>
    <el-form
      class="section-form"
      ref="section-form"
      :model="section"
      label-width="70px"
      :rules="rules"
    >
      <el-form-item label="课程名称" prop="courseName">
        <el-input :value="courseName" autocomplete="off" disabled></el-input>
      </el-form-item>
      <el-form-item label="章节名称" prop="sectionName">
        <el-input v-model="section.sectionName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="章节描述" prop="description">
        <el-input
          v-model="section.description"
          type="textarea"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="章节排序" prop="orderNum">
        <el-input v-model.number="section.orderNum" type="number">
          <template slot="append">数字控制排序，数字越大越靠后</template>
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('on-cancel')">取 消</el-button>
      <el-button type="primary" @click="handleAddSection">确 定</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Form } from 'element-ui'
import { saveOrUpdateSection } from '@/services/course-section'
import Vue from 'vue'
export default Vue.extend({
  name: 'SectionForm',
  props: {
    courseId: {
      type: [String, Number],
      required: true
    },
    courseName: {
      type: String,
      required: true
    },
    editSection: {
      type: Object,
      required: true
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      section: {
        courseId: this.courseId,
        courseName: this.courseName,
        sectionName: '',
        description: '',
        orderNum: 0,
        status: 0
      },
      rules: {
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        sectionName: [
          { required: true, message: '请输入章节名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    if (this.isEdit) {
      this.section = this.editSection
      this.section.courseName = this.courseName
    }
  },
  methods: {
    handleAddSection () {
      (this.$refs['section-form'] as Form).validate(async (valid) => {
        if (valid) {
          await saveOrUpdateSection(this.section);
          (this.$refs['section-form'] as Form).resetFields()
          this.$message.success('操作成功')
          this.$emit('on-success')
        }
      })
    }
  }
})
</script>

<style lang="scss" scoped>
.section-form {
  width: 90%;
  max-width: 660px;
  margin: 0 auto;
}

.dialog-footer {
  text-align: right;
  margin-top: 30px;
}
</style>
